package com.zsj.job;

import com.zsj.config.ConfigBean;
import com.zsj.config.ScheduledCondition;
import com.zsj.mysql.entity.DyMobileRecharge;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.service.NotifyDyService;
import com.zsj.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Conditional;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Component
@Conditional(ScheduledCondition.class)
public class CompensateNotifyJob {

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private NotifyDyService notifyDyService;

    @Autowired
    private IDyMobileRechargeService mobileRechargeService;

    @Scheduled(cron = "0 */5 * * * ?")
    public void autoNotifyDy() {
        if (!"true".equals(configBean.getBatchSwitch())) {
            log.info("批处理开关为:{}，不执行补偿回调任务", configBean.getBatchSwitch());
            return;
        }
        log.info("开始执行补偿回调任务");
        try {
            String month = DateUtil.getCurrentMonth();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String lastTime = fiveMinutesAgo.format(formatter);
            List<DyMobileRecharge> list = mobileRechargeService.getNeedNotify(month, lastTime, configBean.getMaxNotifyTimes());
            // 自动补偿要看一下上个月数据
            List<DyMobileRecharge> lastList = mobileRechargeService.getNeedNotify(DateUtil.getLastMonth(), lastTime, configBean.getMaxNotifyTimes());
            list.addAll(lastList);
            log.info("待补偿的数据量:{}", list.size());
            list.forEach(record -> notifyDyService.notifyDy(record, 1));
        } catch (Exception e) {
            log.info("执行补偿回调任务异常", e);
        }
        log.info("执行补偿回调任务务结束");
    }

}
